/**
 * Created by mrcode on 2015/12/29.
 */
$(function () {
    mdinit();
    WS({
        el: '#tagInput',
        regexp: /^[\u4E00-\u9FA5a-zA-Z0-9]{1,10}$/});
    WS({el: '#catInput',
        regexp: /^[\u4E00-\u9FA5a-zA-Z0-9]{1,10}$/,
        removeEvent:function(v){    //被移除事件 回调
            var $casList = $(".casList span[catName=" + v +"]");
            $casList.toggleClass("label-default");
            $casList.toggleClass("label-primary");
        }
    });

    //分类标签添加事件
    $(".casList span").on("click", function () {
        if(!$(this).hasClass("label-default")){ //如果没有被添加过，则可以添加
            var $catInput = $("#catInput");
            var holder = $catInput.next();
            holder.append($('<a href="javascript:void(0)" class="tag-fm-button">' + $(this).text() + '<em> </em></a>'));
            $catInput.val(holder.text().match(/\S+/g).join(','));
            $(this).toggleClass("label-default");
            $(this).toggleClass("label-primary");
        }
    })
});

/**
 * md 初始化
 */
function mdinit() {
    var testEditor;

    //编辑器皮肤
    function themeSelect(id, themes, lsKey, callback) {
        var select = $("#" + id);
        for (var i = 0, len = themes.length; i < len; i++) {
            var theme = themes[i];
            var selected = (localStorage[lsKey] == theme) ? " selected=\"selected\"" : "";
            select.append("<option value=\"" + theme + "\"" + selected + ">" + theme + "</option>");
        }
        select.bind("change", function () {
            var theme = $(this).val();
            if (theme === "") {
                alert("theme == \"\"");
                return false;
            }
            console.log("lsKey =>", lsKey, theme);
            localStorage[lsKey] = theme;
            callback(select, theme);
        });
        return select;
    };
    //工具栏皮肤切换
    themeSelect("editormd-theme-select", editormd.themes, "theme", function ($this, theme) {
        testEditor.setTheme(theme);
    });
    //编辑区域皮肤切换
    themeSelect("editor-area-theme-select", editormd.editorThemes, "editorTheme", function ($this, theme) {
        testEditor.setCodeMirrorTheme(theme);
        // or testEditor.setEditorTheme(theme);
    });
    //预览区域皮肤切换
    themeSelect("preview-area-theme-select", editormd.previewThemes, "previewTheme", function ($this, theme) {
        testEditor.setPreviewTheme(theme);
    });

    // 设置编辑区域的高度为浏览器可见区域高度
    var clientHeight = document.documentElement.clientHeight;
    $("#test-editormd").parent().height(clientHeight-120);


    //创建md实例，加载文章
    var articleId = $("#articleId").val();
    var userAccount = $("#userAccount").val();
    var bodyT = "/assets/lib/md/test.md";

    var bodySorc = "/" + userAccount + "/article/details/body/" + articleId;
    $.ajax({
        url: bodySorc,
//				data:{Full:"fu"},
        type: "POST",
        dataType: 'text',
        success: function (md) {
            testEditor = editormd("test-editormd", {
                width: "100%",
                height: "100%",
                path: '/assets/lib/md/lib/',
//							theme : "dark",
//							previewTheme : "dark",
//							editorTheme : "pastel-on-dark",
                markdown: md,
                codeFold: true,
                //syncScrolling : false,
                saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
                searchReplace: true,
                //watch : false,                // 关闭实时预览
                htmlDecode: "style,script,iframe|on*",            // 开启 HTML 标签解析，为了安全性，默认不开启
                //toolbar  : false,             //关闭工具栏
                //previewCodeHighlight : false, // 关闭预览 HTML 的代码块高亮，默认开启
                emoji: false,
                taskList: true,
                tocm: true,         // Using [TOCM]
                tex: true,                   // 开启科学公式TeX语言支持，默认关闭
                flowChart: true,             // 开启流程图支持，默认关闭
                sequenceDiagram: true,       // 开启时序/序列图支持，默认关闭,
                //dialogLockScreen : false,   // 设置弹出层对话框不锁屏，全局通用，默认为true
                //dialogShowMask : false,     // 设置弹出层对话框显示透明遮罩层，全局通用，默认为true
                //dialogDraggable : false,    // 设置弹出层对话框不可拖动，全局通用，默认为true
                //dialogMaskOpacity : 0.4,    // 设置透明遮罩层的透明度，全局通用，默认值为0.1
                //dialogMaskBgColor : "#000", // 设置透明遮罩层的背景颜色，全局通用，默认为#fff
                imageUpload: true,
                imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
                imageUploadURL: "/csv/image_upload",
                onload: function () {
                    console.log('onload', this);
                    //this.fullscreen();
                    //this.unwatch();
                    //this.watch().fullscreen();

                    //this.setMarkdown("#PHP");
                    //this.width("100%");
                    //this.height(480);
                    //this.resize("100%", 640);
                }
            });
        }
        ,
        error: function (er) {
            alert.log("发生了一个错误" + er);
        }
    });
    function heckFrom(params) {
        var title = $("#articleTitle").val();
        var summary = $("textarea[name='summary']").val();
        var titleInfo = length_test("article_title",title);
        if(titleInfo){
            MrcodeUi.Alert.sx.danger(titleInfo);
            return false;
        }
        var summaryInfo = length_test("article_summary",summary);
        if(summaryInfo){
            MrcodeUi.Alert.sx.danger(summaryInfo);
            return false;
        }
        return true;
    }
    //编辑提交
    $("#edit_submit").click(function saveArticle() {
        var body = testEditor.getMarkdown();
        var title = $("#articleTitle").val();
        var params = $("#edit-form").serializeArray();
        var pSzie = params.length;
        params[pSzie + 1] = {"name": "title", "value": title};
        params[pSzie + 2] = {"name": "body", "value": body};

        if(!heckFrom(params)){
            return false;
        }
        var formUrl = "/auth/article/edit_submit";
        $.ajax({
            url: formUrl,
            data: params,
            type: "POST",
            dataType: 'json',
            success: function (result) {
                var code = result.code;
                if(code == 0){
                    window.location.href = result.data.redirectUrl;
                }else{
                    MrcodeUi.Alert.sx.danger(result.data);
                }
            },
            error: function (er) {
                alert("发生了一个错误" + er);
            }
        });
    });

    // 打开模态框。data-toggle="modal" data-target="#openArtSubmit" 的方式在ipad上没有效果
    $("#edit_fb").on("click", function () {
        var firstImg = getFirstImg();
        if(firstImg){
            $("#summaryImg").css({  //设置图片预览
                'background-image': 'url(' + firstImg + ')',
                'background-size': 'cover',
                'background-position': 'center center'
            });
            $("input[name='summaryImg']").val(firstImg);
        }else {
            firstImg = '/assets/img/comm/default_article_summaryImg.jpg'
            $("#summaryImg").css({  //设置图片预览
                'background-image': 'url(' + firstImg + ')',
                'background-size': 'cover',
                'background-position': 'center center'
            });
            $("input[name='summaryImg']").val("");
        }

        var title = $("#articleTitle").val();
        if(title){
            $("#a_art_title").text(title);
        }
        $('#openArtSubmit').modal({});
    });

    //获取文章中的第一张图片地址
    function getFirstImg(){
        //获取第一张图片的地址
        var firstImg = null;
        var imgs = $(testEditor.getHTML()).find("img");
        $.each(imgs,function(n,value) {
            if(!$(value).attr("class")){
                console.log("第一个图片：");
                console.log(value);
                firstImg = $(value).attr("src");
                return false;
            }
        });
        return firstImg;
    }
}


